#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SERV_IP "127.0.0.1" /* 服务器可以用 htonl(INADDR_ANY) 自动选择可用IP */
#define SERV_PORT 8000
#define MAX_CONN 100 /* 连接队列最多可以有 100 个客户端在排队等待建立连接 */

int main() {
	char buf[1024];
	int n;
	int sockfd, clientfd;
	struct sockaddr_in serv_addr, client_addr;
	socklen_t socklen;

	sockfd = socket(AF_INET, SOCK_STREAM, 0); /* IPv4 协议， TCP 协议*/
	if (sockfd == -1) {
		perror("socket");
		return -1;
	}
	bzero(&serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);  /* 指定端口号 */
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* 自动选择可用IP */
	if (bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
		perror("bind");
		return -1;
	}
	if (listen(sockfd, MAX_CONN) < 0) {
		perror("listen");
		return -1;
	}

	socklen = sizeof(client_addr);	
	clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &socklen);
	if (clientfd < 0) {
		perror("accept");
		return -1;
	}
	inet_ntop(AF_INET, &client_addr, buf, INET_ADDRSTRLEN);
	printf("client IP is: %s, client port is: %d\n", buf, ntohs(client_addr.sin_port));
	while(1) {	
		n = read(clientfd, buf, sizeof(buf));
		for (int i = 0; i < n; i++) {
			buf[i] = toupper(buf[i]);
		}
		write(clientfd, buf, n);
	}
	close(clientfd);
	close(sockfd);

	return 0;
}
